package com.example.demo.ribbon;

import java.util.List;
import java.util.Optional;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.example.demo.component.RouteFileStore;
import com.example.demo.context.RibbonDefinition;
import com.example.demo.context.RouteDefinitionWrapper;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ConfigurationBasedServerList;
import com.netflix.loadbalancer.Server;

/**
 * @author sleepforests
 * Created on 2019-07-18
 */
public class MyConfigurationBasedServerList extends ConfigurationBasedServerList {
    private final Logger logger =
            LoggerFactory.getLogger(MyConfigurationBasedServerList.class);

    private IClientConfig clientConfig;

    public MyConfigurationBasedServerList(IClientConfig config) {
        super.initWithNiwsConfig(config);

        logger.debug("=======初始化MyConfigurationBasedServerList=======");
        clientConfig = config;
    }

    @Override
    public List<Server> getUpdatedListOfServers() {

        RouteDefinitionWrapper routeDefinitionWrapper = RouteFileStore.get();
        if (routeDefinitionWrapper != null
                && routeDefinitionWrapper.getRibbonDefinitionList() != null
                && routeDefinitionWrapper.getRibbonDefinitionList().size() > 0) {
            Optional<RibbonDefinition> ribbonDefinitionOptional =
                    routeDefinitionWrapper.getRibbonDefinitionList()
                            .stream()
                            .filter(ribbonDefinition -> StringUtils.equals(ribbonDefinition.getClientName(), clientConfig.getClientName()))
                            .findFirst();
            if (ribbonDefinitionOptional.isPresent()) {
                return super.derive(ribbonDefinitionOptional.get().getListOfServers());
            }
        }

        return super.getUpdatedListOfServers();
    }
}
